package cn.orange.ch08_backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * LC131.分割回文串
 */
public class LC131 {
    public List<List<String>> partition(String s) {
        List<List<String>> ans = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        backtracking(0, s, path, ans);
        return ans;
    }

    private void backtracking(int start, String s, LinkedList<String> path, List<List<String>> ans) {
        if (start >= s.length()) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            String sub = s.substring(start, i + 1);
            if (!isPalindrome(sub)) continue;
            path.add(sub);
            backtracking(i + 1, s, path, ans);
            path.removeLast();
        }
    }

    private boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i <= j) {
            if (s.charAt(i) != s.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }

    public static void main(String[] args) {
        LC131 alg = new LC131();
        System.out.println(alg.partition("aab"));
        System.out.println(alg.partition("a"));
    }
}
